import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { doubleValidate,validatePhone} from '~/utils/validate.js'
import subContract from './sub-contract.vue'
import {save, update, get, validateCode} from '../api/contract'
export default {
    name: "edit-data",
    created() {
        this.projectTypes = this.getDict('epc_project_type')
        this.contractTypes = this.getDict('epc_contract_type')
        this.projectForm.projectContract.projectContractId = this.$route.params.projectContractId
        if (this.projectForm.projectContract.projectContractId) {
            this.isAdd = false
            this.handleInit(this.projectForm.projectContract.projectContractId)
        }
    },
    mixins: [BaseLoad],
    components: {
        subContract
    },
    data() {
        let validateContractNum = (rule, value, callback) => {
            if (!value) {
                callback()
            }
            this.validateCodeOnly(value, callback)
        };
        return {
            dialogVisible: false,
            editDataShow: false,
            subContractsFlag: true,
            isAdd: true,
            subContractsIndex: 0,
            symbolType: '',
            engineering: {
                projectId: '',
                projectTenderId: '',
                projectName: '',
                projectAddress: '',
                projectType: ''
            },
            projectForm: {
                estimateAmount: '',
                projectContract: {
                    projectId: '',
                    projectTenderId: '',
                    projectName: '',
                    projectAddress: '',
                    projectType: '',
                    projectContractId: '',
                    contractNum: '',
                    contractType: '',
                    contractAmount: '',
                    unitPrice: '',
                    contractDate: '',
                    startDate: '',
                    endDate: '',
                    partybUnit: '',
                    partybContact: '',
                    partybPhone: '',
                    supplement: '',
                    signDate: '',
                    suppleStart: '',
                    suppleEnd: '',
                    suppleAmount: '',
                    remarks: ''
                },
                subContracts: []
            },
            registrationForm: {},
            projectTypes: [],
            contractTypes: [],
            supplements: [
                {
                    value: '1',
                    label: '是'
                },
                {
                    value: '0',
                    label: '否'
                }
            ],
            fileList: [],
            supplementaryFileList: [],
            // 选择弹窗属性数据
            chooseDialogAttrs: {},
            engineering_rules: {
                projectName: [{required: true, message: '请输入工程名称', trigger: 'change'}],
                projectAddress: [{required: true, message: '请输入工程地址', trigger: 'blur'}],
                projectType: [{required: true, message: '请选择工程类型', trigger: 'blur'}]
            },
            projectContract_rules: {
                contractNum: [{required: true, message: '请输入合同编号', trigger: 'blur'},
                    { validator: validateContractNum, trigger: "blur"}],
                contractType: [{required: true, message: '请选择合同类型', trigger: 'change'}],
                contractAmount: [{required: true, message: '请输入合同金额', trigger: 'blur'},
                    { validator: doubleValidate, trigger: "blur"}],
                contractDate: [{required: true, message: '请选择签订日期', trigger: 'blur'}],
                startDate: [{required: true, message: '请选择合同开始日期', trigger: 'blur'}],
                endDate: [{required: true, message: '请选择合同结束日期', trigger: 'blur'}],
                partybUnit: [{required: true, message: '请输入乙方单位名称', trigger: 'blur'}],
                partybContact: [{required: true, message: '请输入联系人', trigger: 'blur'}],
                partybPhone: [{required: true, message: '请输入联系电话', trigger: 'blur'},
                    { validator: validatePhone, trigger: "blur"}],
                supplement: [{required: true, message: '请选择是否有补充协议', trigger: 'change'}],
                signDate: [{required: true, message: '请选择补充协议签订日期', trigger: 'blur'}],
                suppleStart: [{required: true, message: '请选择补充协议期限', trigger: 'blur'}],
                suppleAmount: [{required: true, message: '请输入补充协议金额', trigger: 'blur'},
                    { validator: doubleValidate, trigger: "blur"}]
            }
        }
    },
    methods: {
        //保存
        commit() {
            const engineering = new Promise((resolve, reject) => {
                this.$refs['engineering'].validate((valid) => {
                    if (valid) resolve();
                })
            })
            const projectContract = new Promise((resolve, reject) => {
                this.$refs['projectContract'].validate((valid) => {
                    if (valid) resolve();
                })
            })
            if (this.projectForm.estimateAmount) {
                if (this.projectForm.projectContract.suppleAmount) {
                    if (Number(this.projectForm.projectContract.suppleAmount) + Number(this.projectForm.projectContract.contractAmount) > Number(this.projectForm.estimateAmount)) {
                        return this.$message.error('合同金额与补充协议金额之和不能超过概算批复文件金额！')
                    }
                } else {
                    if (Number(this.projectForm.projectContract.contractAmount) > Number(this.projectForm.estimateAmount)) {
                        return this.$message.error('合同金额不能超过概算批复文件金额！')
                    }
                }
            }
            Promise.all([engineering, projectContract]).then(() => {
                if (this.projectForm.projectContract.supplement === '1') {
                    if (this.$refs.supplementaryUpload.loadFileList.length > 0 || this.supplementaryFileList.length > 0) {
                        this.$refs.supplementaryUpload.submit()
                    } else {
                        this.$message.warning('请上传补充协议附件！')
                    }
                } else {
                    this.$refs.normalUpload.submit()
                    // this.saveFormData()
                }
            })
        },
        //补充协议文件上传
        supplementarySuccess(response, file, fileList){
            //文件上传成功，开始保存表单
            if (fileList !== undefined && fileList.length > 0) {
                if (response.data) {
                    this.projectForm.projectContract.projectContractId = response.data
                    this.$refs.normalUpload.submit('normal',this.projectForm.projectContract.projectContractId)
                } else {
                    this.err('文件上传失败')
                }
            } else {
                this.$refs.normalUpload.submit()
            }
        },
        //文件上传
        onSuccess(response, file, fileList){
            //文件上传成功，开始保存表单
            if (fileList !== undefined && fileList.length > 0) {
                if (response.data) {
                    this.saveFormData()
                } else {
                    this.err('文件上传失败')
                }
            } else {
                this.saveFormData()
            }
        },
        saveFormData () {
            let obj,subContracts,otherExpenses,arr = []
            this.projectForm.subContracts.map(it => {
                otherExpenses = it.otherExpenses
                this.$delete(it, 'otherExpenses')
                subContracts = it
                obj = {subContracts,otherExpenses}
                arr.push(obj)
            })
            this.projectForm.subContracts = arr
						this.projectForm.projectContract.projectId = this.engineering.projectId
						this.projectForm.projectContract.projectTenderId = this.engineering.projectTenderId
						this.projectForm.projectContract.projectName = this.engineering.projectName
						this.projectForm.projectContract.projectAddress = this.engineering.projectAddress
						this.projectForm.projectContract.projectType = (this.engineering.projectType === 'EPC') ? '20' : '10'
						this.projectForm.projectContract.suppleEnd = this.projectForm.projectContract.suppleStart[1]
						this.projectForm.projectContract.suppleStart = this.projectForm.projectContract.suppleStart[0]
            this.loadAction('数据加载中')
            if (this.isAdd) {
                save(this.projectForm).then((rep) => {
                    this.loadClose()
                    this.$message.success("保存成功");
                    this.closeNowRouter()
                }).catch((e) => {
                    this.loadClose()
                    this.$message.error("保存失败");
                })
            } else {
                update(this.projectForm).then((rep) => {
                    this.loadClose()
                    this.$message.success("修改成功");
                    this.closeNowRouter()
                }).catch((e) => {
                    this.loadClose()
                    this.$message.error("修改失败");
                });
            }
        },
        closeNowRouter() {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            // this.$parent.$children[2].closeTab('current')
            //跳转
            this.$router.push("/wy-operate/epc/contract");
        },
        //选择工程名称
        handleClickProjectName() {
            const dictVal_unitType = (row, column, cellValue) => {
                let obj = this.getDict('epc_project_type').find(p => p.value == cellValue);
                if (obj) {
                    return obj.label;
                }
                return "";
            }
            this.chooseDialogAttrs = {
                title: '选择工程',
                placeholder: '请输入工程名称',
                url: '/api/epcproject/waitInputContractPage',
                primaryKey: 'projectName',
                showData: [
                    { prop: 'projectName', label: '工程名称', width: '200', align: 'center'},
                    { prop: 'projectAddress', label: '工程地址', align: 'center'},
                    { prop: 'projectType', label: '工程类型', align: 'center',formatter: dictVal_unitType},
                    { prop: 'agentContact', label: '单位联系人', align: 'center'},
                    { prop: 'agentPhone', label: '联系电话', align: 'center'}
                ]
            }
            this.$nextTick(() => {
                this.$refs.chooseDialog.show()
            })
        },
        //工程名称确定
        handleClickAdd(item) {
            if (this.projectForm.projectContract.projectName) {
                this.$confirm('一次只能添加一条数据，该操作将覆盖上条数据,是否继续?', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(() => {
                    this.engineering = item
                    this.engineering.projectType = this.getCardTypeValue(item.projectType,this.projectTypes)
                    this.$message.success('添加成功！')
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    })
                })
            } else {
                this.engineering = item
                this.engineering.projectType = this.getCardTypeValue(item.projectType,this.projectTypes)
                this.$message.success('添加成功！')
            }
        },
        //对应value取label
        getCardTypeValue(num, sum){
            let arr = sum.filter(e=>e.value === num)
            if (arr.length > 0) {
                return arr[0].label
            } else {
                return num
            }
        },
        //子合同添加
        superInforAdd() {
            this.editDataShow = true
            this.$nextTick(() => {
                this.$refs.subContract.showDialog()
            })
            this.subContractsFlag = true
            this.subContractsIndex = 0
        },
        //子合同编辑
        handleClickEdit(item) {
            this.editDataShow = true
            this.$nextTick(() => {
                this.$refs.subContract.showDialog(item)
            })
            this.subContractsFlag = false
            this.subContractsIndex = item.$index
        },
        //子合同删除
        handleClickDelete(index,rows) {
            rows.splice(index, 1)
        },
        //子合同保存
        handleDialogsSave(item) {
            if (this.subContractsFlag) {
                this.projectForm.subContracts.push(item.arr)
            } else {
                this.projectForm.subContracts[this.subContractsIndex] = item.arr
            }
            this.handleClose()
        },
        //子合同关闭弹框组件
        handleClose() {
            this.editDataShow = false
        },
        //合同开始结束日期校验
        handleChooseStartDate(){
            if (new Date(this.projectForm.projectContract.startDate) > new Date(this.projectForm.projectContract.endDate)) {
                this.$message.error('合同开始日期不能晚于合同结束日期')
                this.projectForm.projectContract.startDate = ''
            }
        },
        handleChooseEndDate(){
            if (new Date(this.projectForm.projectContract.startDate) > new Date(this.projectForm.projectContract.endDate)) {
                this.$message.error('合同结束日期不能早于合同开始日期')
                this.projectForm.projectContract.endDate = ''
            }
        },
        //回显
        handleInit(id) {
            get(id).then(res => {
                if (res.data.code === 0) {
                    this.projectForm = res.data.data
                    this.engineering = this.projectForm.projectContract
                    let obj,arr = []
                    this.projectForm.subContracts.map(e =>{
                        obj = {...e.subContracts}
                        obj.otherExpenses = e.otherExpenses
                        arr.push(obj)
                    })
                    this.projectForm.subContracts = arr
                    this.engineering.projectType = this.getCardTypeValue(this.projectForm.projectContract.projectType,this.projectTypes)
                    this.projectForm.projectContract.suppleStart = this.projectForm.projectContract.suppleStart && this.projectForm.projectContract.suppleEnd ? [this.projectForm.projectContract.suppleStart,this.projectForm.projectContract.suppleEnd] : []

                    if(this.projectForm.projectContract.supplement == "0"){
                        //    清空补充协议相关的值
                        this.projectForm.projectContract.signDate = ''
                        this.projectForm.projectContract.suppleStart = ''
                        this.projectForm.projectContract.suppleEnd = ''
                        this.projectForm.projectContract.suppleAmount = ''
                    }
                }
            })
        },
        //补充协议附件回显过滤
        supplementaryLoadCompleted(data) {
            this.$refs.supplementaryUpload.loadFileList = data.filter(item => item.module === 'supplementary')
        },
        //附件回显过滤
        normalLoadCompleted(data) {
            this.$refs.normalUpload.loadFileList = data.filter(item => item.module === 'normal')
        },
        //验证合同编号是否存在
        validateCodeOnly (value, callback) {
            validateCode({ "vType": '1', "code": value, 'id': this.projectForm.projectContract.projectContractId}).then(rep => {
                let vr = rep.data.data
                if (vr === 0) {
                    return callback();
                } else {
                    return callback(new Error("合同编号不能重复"));
                }
            })
        },
        //如果有补充协议，且补充协议的金额能超过原有合同金额的10%,给出提示，提示信息“请确认此XXX合同（原合同金额XX元）已超过原合同10%（原合同*10%元）”，这里仅仅给出提示，这里可以保存成功
        handleSuppleAmount() {
            if (Number(this.projectForm.projectContract.suppleAmount) > Number(this.projectForm.projectContract.contractAmount) * 0.1) {
                this.$message.warning('请确认此'
                    + this.projectForm.projectContract.contractNum
                    + '合同（原合同金额'
                    + this.projectForm.projectContract.contractAmount
                    + '元）已超过原合同10%（原合同*10%元）')
            }
            if (this.projectForm.estimateAmount) {
                if (Number(this.projectForm.projectContract.suppleAmount) + Number(this.projectForm.projectContract.contractAmount) > Number(this.projectForm.estimateAmount)) {
                    this.$message.error('合同金额与补充协议金额之和不能超过概算批复文件金额！')
                }
            }
        },
        //是否有补充协议发送改变时
        changeSupplement(val) {
           // 0 否，1是
            if(val == "0"){
            //    清空补充协议相关的值
                this.projectForm.projectContract.signDate = ''
                this.projectForm.projectContract.suppleStart = ''
                this.projectForm.projectContract.suppleEnd = ''
                this.projectForm.projectContract.suppleAmount = ''
            }
        },
        handleContractAmount() {
            if (this.projectForm.projectContract.suppleAmount) {
                if (Number(this.projectForm.projectContract.suppleAmount) > Number(this.projectForm.projectContract.contractAmount) * 0.1) {
                    this.$message.warning('请确认此'
                        + this.projectForm.projectContract.contractNum
                        + '合同（原合同金额'
                        + this.projectForm.projectContract.contractAmount
                        + '元）已超过原合同10%（原合同*10%元）')
                }
                if (this.projectForm.estimateAmount) {
                    if (Number(this.projectForm.projectContract.suppleAmount) + Number(this.projectForm.projectContract.contractAmount) > Number(this.projectForm.estimateAmount)) {
                        this.$message.error('合同金额与补充协议金额之和不能超过概算批复文件金额！')
                    }
                }
            } else {
                if (this.projectForm.estimateAmount) {
                    if (Number(this.projectForm.projectContract.contractAmount) > Number(this.projectForm.estimateAmount)) {
                        this.$message.error('合同金额不能超过概算批复文件金额！')
                    }
                }
            }
        }
    }
}
